'use strict'

const titbit=require('titbit');
const pg=require('pg');
const dbcfg=require('./dbconfig');

const psql=new pg.Pool(dbcfg);

let cert_path='/usr/local/share';
const app=new titbit({
    debug:true,
    globalLog:true,  //开启全局日志
    cert:`${cert_path}/api.lzjlw.top.pem`,
    key:`${cert_path}/api.lzjlw.top.key`
});

app.get('/movie',async c=>{
    let sqltext=`select * from movie`;
    let res=await psql.query(sqltext);
    c.send(res.rows);
})

app.get('/movie/:id',async c=>{
    let sqltext=`select * from movie where id=$1`;
    let res=await psql.query(sqltext,[c.param.id]);
    if(res.rowCount==0){
        return c.status(404).send('content not found');
    }
    c.send(res.rows[0]);
})

app.post('/movie',async c=>{
    let {moviename,introduction,showtime,totaltime}=c.body;
    let tm=Date.now();
    let sqltext=`insert into movie(id,name,introduction,showtime,totaltime) values($1,$2,$3,$4,$5)`;
    let res=await psql.query(sqltext,[tm,moviename,introduction,showtime,totaltime]);
    if(res.rowCount==0){
        return c.status(404).send('insert failed');
    }
    c.send(c.body);
})

app.delete('movie/:id',async c =>{
    let sqltext=`delete from movie where id=$1`;
    let res=await psql.query(sqltext,[c.param.id]);
    if(res.rowCount==0){
        return c.status(404).send(`删除失败`);
    }
    c.send('删除成功');
})
app.run(3456)
